package com.vt.common.security.handler;

import com.vt.common.security.util.parser.DictionaryParser;
import com.vt.common.security.util.parser.UNameParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @Auther: panZha
 * @Date: 2018/11/9 14:19
 * @Description:
 */
@Component
@RestControllerAdvice
public class ServiceResponseBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParam, Class aClass) {
        return true;
    }

    @Autowired
    UNameParser uNameParseUtil;
    @Autowired
    DictionaryParser dictionaryParser;

    @Override
    public Object beforeBodyWrite(Object returnVal, MethodParameter methodParam, MediaType media, Class aClass, ServerHttpRequest request, ServerHttpResponse response) {
        if (isWhiteURL(request))
            return returnVal;

        uNameParseUtil.parse(returnVal);
        dictionaryParser.parse(returnVal);
        return returnVal;
    }

    /**
     * 白名单
     */
    private String[] whiteListURLs = {"/oauth/check_token", "/user/info/**"};
    private final PathMatcher pathMatcher = new AntPathMatcher();

    private boolean isWhiteURL(ServerHttpRequest request) {
        String currentURL = request.getURI().getPath();

        for (String whiteURL : whiteListURLs) {
            if (pathMatcher.match(whiteURL, currentURL)) {
                return true;
            }
        }
        return false;
    }
}
